<template>
    <div>
      <!--    面包屑导航区域-->
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>班级管理</el-breadcrumb-item>
        <el-breadcrumb-item>查询班级信息</el-breadcrumb-item>
      </el-breadcrumb>
      <el-card>
        <!--      搜索与添加区域-->
        <el-row :gutter="20">
          <el-col :span="10">
            <el-input placeholder="请输入内容" v-model="queryInfo.searchInfo" clearable @clear="getClassList">
              <el-button slot="append" icon="el-icon-search"></el-button>
            </el-input>
          </el-col>
          <el-col :span="5">
            <el-button class="new_btn" @click="JumpToAdd">
              <svg class="icon_add" viewBox="0 0 20 20" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
                <polygon id="路径" fill="#FFFFFF" points="11.34223 8.55450006 11.34223 1.52678484 8.5311359 1.52678484 8.5311359 8.55450006 1.50342068 8.55450006 1.50342068 11.3655941 8.5311359 11.3655941 8.5311359 18.3933093 11.34223 18.3933093 11.34223 11.3655941 18.3699652 11.3655941 18.3699652 8.55450006"></polygon>
              </svg>
              创建新班级
            </el-button>
          </el-col>
        </el-row>
        <!--        班级列表区域-->
        <el-table
          v-loading="loading"
          element-loading-text="拼命加载中"
          element-loading-spinner="el-icon-loading"
          :default-sort = "{prop: 'id', order: 'ascending'}" :data="pageclasslist" :stripe="true">
          <el-table-column type="index" label="序号" width="50" align="center"></el-table-column>
          <el-table-column align="center" label="+" width="40" fixed="left">
            <template slot-scope="scope">
              <!--              添加题目集到该班级按钮-->
              <el-popover
                placement="bottom"
                title="添加题目集"
                width="100"
                trigger="hover"
                content="添加题目集到该班级">
                <el-button slot="reference" style="color: #545c99" type="text" icon="el-icon-plus" size="mini" :enterable="false" @click="addClassToSet(scope.row.id)"></el-button>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="id" label="编号"  sortable width="80px"></el-table-column>
          <el-table-column align="center" label="班级名">
            <template slot-scope="scope">
              <el-tooltip effect="dark" content="查看该班级学生">
                <el-button type="text" @click="JumpTo(scope.row.id, scope.row.name)">{{scope.row.name}}</el-button>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="count" label="班级人数" sortable>
            <template slot-scope="scope">
              <span v-if="scope.row.count === 0" style="color: red">{{scope.row.count}}</span>
              <span v-else style="color: #545c99">{{scope.row.count}}</span>
              人
            </template>
          </el-table-column>
          <!--        操作-->
          <el-table-column align="center" label="操作" width="120" fixed="right">
            <template slot-scope="scope">
              <!--              修改班级名称按钮-->
              <el-tooltip effect="dark" content="修改班级名称" placement="top">
                <el-button style="background-color: #545c64;color: white" icon="el-icon-edit" size="mini" :enterable="false" @click="showNameDialog(scope.row.id)"></el-button>
              </el-tooltip>
              <!--              删除班级按钮-->
              <el-tooltip effect="dark" content="删除班级" placement="bottom">
                <el-button type="danger" icon="el-icon-delete" size="mini" :enterable="false" @click="removeClassById(scope.row.id)"></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <!--      分页区域-->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryInfo.pagenum"
          :page-sizes="[10, 20, 30]"
          :page-size="queryInfo.pagesize"
          hide-on-single-page
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </el-card>
      <!--    修改班级名称的对话框-->
      <el-dialog
        title="修改班级名称"
        :visible.sync="nameDialogVisible"
        width="45%" @close="nameDialogClosed">
        <!--      内容主体区域-->
        <el-form :model="nameForm" status-icon ref="nameFormRef" label-width="100px">
          <el-form-item label="班级编号">
            <el-input v-model="nameForm.id" disabled></el-input>
          </el-form-item>
          <el-form-item label="班级新名称" prop="name" required>
            <el-input v-model="nameForm.name" placeholder="请输入班级名称" @keyup.enter.native="editName" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <!--      底部区域-->
        <span slot="footer" class="dialog-footer">
           <el-row>
          <el-col :span="4" :offset="5" >
            <el-button class="white_btn" @click="resetName">重 置</el-button>
          </el-col>
          <el-col :span="4" :offset="5">
            <el-button class="new_btn" @click="editName">修 改</el-button>
          </el-col>
        </el-row>
        </span>
      </el-dialog>
<!--      展示该班级所有学生-->
      <el-dialog style="z-index: 10" :title="ClassForm.name + '学生信息'"
                 :visible.sync="IsShowStu" width="50%"
                 @close="JumpClosed" class="role-mask">
<!--        表格-->
        <el-row style="font-size: 1.1em;margin-top: 10px">
          <el-col :span="12">
            <b>授课老师：</b>{{this.ClassForm.teacher}}
          </el-col>
          <el-col :span="6" :offset="6" v-if="StuForm[0]">
            <el-button @click="DetailInfo" type="text" style="color: #545c99">
              <b>点击查看详情</b>
            </el-button>
          </el-col>
        </el-row>
        <el-table
          height="280"
          v-loading="loading1"
          element-loading-text="拼命加载中"
          element-loading-spinner="el-icon-loading"
          :default-sort="{ prop: 'username', order: 'descending'}" :data="StuForm">
          <el-table-column fixed type="index" label="#"></el-table-column>
          <el-table-column align="center" prop="username" sortable label="学号"></el-table-column>
          <el-table-column align="center" prop="name" label="姓名"></el-table-column>
        </el-table>
        <!--      底部区域-->
        <span slot="footer" class="dialog-footer">
            <el-row :gutter="20">
                <el-col :span="3" :offset="10">
                      <el-button class="new_btn" @click="JumpClosed">关 闭</el-button>
                </el-col>
            </el-row>
        </span>
      </el-dialog>

      <!--    添加题目集到该班级里-->
      <el-dialog
        title="添加题目集到该班级"
        :visible.sync="addClassToVisible"
        width="58%" @close="addClassToClosed">
        <!--      内容主体区域-->
        <el-form  status-icon :model="addClassForm" ref="addClassFormRef">
          <el-form-item label="选择题目集" label-width="42%" prop="setId" required>
            <el-autocomplete
              v-model="name"
              :fetch-suggestions="querySearchAsync"
              placeholder="请输入要添加的题目集"
              @select="handleSelect"
            ></el-autocomplete>
          </el-form-item>
        </el-form>
        <!--      底部区域-->
        <span slot="footer" class="dialog-footer">
        <el-row>
          <el-col :span="4" :offset="5" >
            <el-button class="white_btn" @click="resetAdd">重 置</el-button>
          </el-col>
          <el-col :span="4" :offset="5">
            <el-button class="new_btn" @click="addClass">添 加</el-button>
          </el-col>
        </el-row>
        </span>
      </el-dialog>
    </div>
</template>

<script>
export default {
  name: 'ClassInfo',
  data () {
    return {
      // 获取用户列表的参数对象
      queryInfo: {
        // 模糊搜索
        searchInfo: '',
        // 当前页数
        pagenum: 1,
        pagesize: 10
      },
      classlist: [],
      total: 0,
      nameDialogVisible: false,
      // 班级名称
      nameForm: {
        id: '',
        name: ''
      },
      // 通过班级查学生
      ClassForm: {
        id: '',
        name: '',
        teacher: ''
      },
      IsShowStu: false,
      StuForm: [],
      loading: true, // 班级加载
      loading1: true, // 班级学生加载
    //  添加班级到题目集窗口
      addClassToVisible: false, //添加班级到题目集窗口
      addClassForm:{
        classId:'',
        setId:''
      },
      // 远程拉取数据
      SetName: [],
      timeout:  null,
      name: '',
    }
  },
  created () {
    this.getClassList()
  },
  methods: {
    async getClassList () {
      const { data: res } = await this.$http.get('/class/allOfTeacher/' + localStorage.getItem('username'))
      if (res.status !== 200) {
        return this.$message.error('获取班级列表失败!')
      }
      this.classlist = res.data
      if (this.classlist.length === res.data.length){
        this.total = res.data.length
        this.loading = false
      }
    },
    // 监听 pagesize 改变的事件
    handleSizeChange (newSize) {
      this.queryInfo.pagesize = newSize
      this.getClassList()
    },
    // 监听页码值改变的事件
    handleCurrentChange (newPage) {
      // console.log(newPage)
      this.queryInfo.pagenum = newPage
      this.getClassList()
    },
    resetName () {
      this.$refs.nameFormRef.resetFields()
    },
    showNameDialog (id) {
      this.nameDialogVisible = true
      this.nameForm.id = id
    },
    // 监听修改班级名称对话框的关闭事件
    nameDialogClosed () {
      this.$refs.nameFormRef.resetFields()
    },
    // 点击按钮，修改名称
    editName () {
      this.$refs.nameFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put('/class/updateName/', {
          classId: this.nameForm.id,
          className: this.nameForm.name
        })
        console.log(this.nameForm.name)
        console.log(this.nameForm.id)
        if (res.status !== 200) {
          return this.$message.error('更新班级名称失败!')
        }
        this.$message.success('更新班级名称成功！')
        this.nameDialogVisible = false
        this.getClassList()
      })
    },
    async removeClassById (id) {
      const confirmResult = await this.$confirm('此操作将永久删除该班级, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 若用户确认删除，则返回值为字符串 confirm
      // 若取消删除，返回 cancel
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete('/class/delete/' + id)
      if (res.status !== 200) {
        return this.$message.error('删除班级失败！')
      }
      this.$message.success('删除班级成功!')
      this.getClassList()
    },
    async JumpTo (id, name) {
      console.log(id)
      const { data: res } = await this.$http.get('/student/allStudentOfClass/' + id)
      if (res.status !== 200) {
        return this.$message.error('获取班级学生列表失败!')
      }
      this.StuForm = res.data.student
      this.ClassForm.id = id
      this.ClassForm.name = name
      this.ClassForm.teacher = res.data.class.teacher
      this.IsShowStu = true
      console.log(res.data)
      console.log(this.StuForm)
      if (this.StuForm.length === res.data.student.length){
        this.loading1 = false
      }
    },
    JumpClosed () {
      this.IsShowStu = false
    },
    JumpToAdd(){
      window.sessionStorage.setItem('activePath', 'AddClass')
      this.$router.push("AddClass")
      this.$router.go(0)
    },
    DetailInfo(){
      var classId = this.ClassForm.id
      var name = this.ClassForm.name
      this.$router.push({path: '/StuDetails', query: {classId: classId, name: name}})
    },
    addClassToSet(id){
      this.addClassToVisible = true
      this.addClassForm.classId = id
      console.log(id)
    },
    resetAdd () {
      this.$refs.addClassFormRef.resetFields()
      this.name = ''
    },
    addClassToClosed(){
      this.name = ''
      this.$refs.addClassFormRef.resetFields()
    },
    // 加载所有班级
    async loadAll() {
      const { data: res } = await this.$http.get('/set/findByTeach/' + localStorage.getItem('username'))
      console.log(res.data)
      if (res.status !== 200) {
        return this.$message.error(res.msg)
      }
      var arr = []
      res.data.forEach(function (item) {
        arr.push({'setId': item.setId , 'value': item.setName})
      })
      this.SetName  = arr
      console.log(arr)
      return arr
    },
    // 远程获取数据
    querySearchAsync(queryString, cb) {
      var SetName = this.SetName;
      var results = queryString ? SetName.filter(this.createStateFilter(queryString)) : SetName;
      clearTimeout(this.timeout);
      this.timeout = setTimeout(() => {
        cb(results);
      }, 3000 * Math.random());
    },
    createStateFilter(queryString) {
      return (state) => {
        return (String(state.value).toLowerCase().indexOf(queryString.toLowerCase()) > -1);
      };
    },
    handleSelect(item) {
      this.addClassForm.setId = item.setId
      console.log(this.addClassForm.setId);
    },
    async addClass (){
      console.log(this.addClassForm)
      const { data: res } = await this.$http.post('/class/addToSet/',this.addClassForm )
      if (res.status !== 200) {
        return this.$message.error(res.msg)
      }
      this.$message.success('添加成功!')
      this.addClassToVisible = false
    },
  },
  computed: {
    pageclasslist: function () {
      var search = this.queryInfo.searchInfo
      if (search) {
        return this.classlist.filter(function (data) {
          return Object.keys(data).some(function (key) {
            return String(data[key]).toLowerCase().indexOf(search) > -1
          })
        })
      }
      return this.classlist.slice((this.queryInfo.pagenum - 1) * this.queryInfo.pagesize, this.queryInfo.pagenum * this.queryInfo.pagesize)
    }
  },
  mounted() {
    this.SetName = this.loadAll();
  }
}
</script>

<style scoped>
  /* 顶部下划线 */
  .role-mask .el-dialog__header{
    border-bottom: 2px solid cornflowerblue;
    padding: 20px;
  }
  .role-mask .el-dialog__title{
    font-size: 19px;
    color: #3A68C6;
  }
  .new_btn{
    background: #545c64;
    color: white;
    letter-spacing: 2px;
  }
  .new_btn:hover,.new_btn:focus{
    background: #545c99;
    color: ghostwhite;
    letter-spacing: 2px;
  }
  .icon_add{
    width: 24px;
    height: 24px;
    padding-right: 4px;
    vertical-align:middle;
  }
</style>
